<?php
/*
	本插件：$this->model('model')->方法名();
	其他地方调用：model('jy_taobaoke/model')->方法名();
	文档：https://aff-open.taobao.com/?spm=a219a.13922336.0.0.373c24adCVwEOi#!/document
*/
namespace jy_taobaoke;
defined('BY_JYA') or exit('error');
class model extends \plugin{
	
	public function hq_taoid($taourl) {//根据淘宝地址获取淘宝商品id
		$strurl = strtolower ($taourl);
		if (strpos ($taourl,'itemId') !== false) {
			$arr = explode ('itemId=', $taourl);
			$arr = explode ('&', $arr[1]);
			$NO = $arr[0];
			return $NO;
		}
		return '';
	}
	//生成淘口令
	public function getcode($url,$mid=0){
		if(!$url){
			return false;
		}
		include ROOT_D.'/addons/jy_taobaoke/sdk/TopSdk.php';
		$c = new \TopClient;
		$basic=$this->plugin_setting('basic');
		$basic['codetitle']=$basic['codetitle']?:'您的朋友给您分享了一个商品';
		$c->appkey = $basic['appkey'];
		$c->secretKey = $basic['secret'];
		$req = new \TbkTpwdCreateRequest;
		$req->setUserId($mid);
		$req->setText($basic['codetitle']);
		$req->setUrl($url);
		$req->setLogo(tomedia($basic['logo']));
		$ext=ijson_encode(array('mid'=>$mid));
		$req->setExt($ext);
		$re = $c->execute($req);
		//$re = json_decode($resp,true);
		$re   = (array)$re;
		$re   = (array)$re['data'];
		$re   = $re['model'];
		return $re;
	}
	//生成短链接 taobao.tbk.spread.get
	public function getduanurl($url){
		include ROOT_D.'/addons/jy_taobaoke/sdk/TopSdk.php';
		$c = new \TopClient;
		$basic=$this->plugin_setting('basic');
		$c->appkey = $basic['appkey'];
		$c->secretKey = $basic['secret'];
		$req = new \TbkSpreadGetRequest;
		$requests = new \TbkSpreadRequest;
		$requests->url=$url;
		$req->setRequests(json_encode($requests));
		$re = $c->execute($req);
		//$re = json_decode($resp,true);
		$re   = (array)$re;
		if($re['code']){
			exi('转化短链失败:'.$re['code'].'，错误详情：'.$re['sub_msg'].$re['msg'],'error');
		}
		$re   = (array)$re['results'];
		$re   = (array)$re['tbk_spread'];
		return $re['content'];
	}
	public function getgoodsinfo($id){
		include ROOT_D.'/addons/jy_taobaoke/sdk/TopSdk.php';
		$c = new \TopClient;
		$basic=$this->plugin_setting('basic');
		$c->appkey = $basic['appkey'];
		$c->secretKey = $basic['secret'];
		$req = new \TbkItemInfoGetRequest;
		$req->setNumIids($id);
		$req->setPlatform("1");
		$re = $c->execute($req);
		//$re = json_decode($resp,true);
		$re   = (array)$re;
		if($re['code']){
			exi('采集失败:'.$re['code'].'，错误详情：'.$re['sub_msg'].$re['msg'],'error');
		}
		$re   = (array)$re['results'];
		$re   = (array)$re['n_tbk_item'];
		return $re;
	}
	//taobao.tbk.dg.optimus.material( 淘宝客-推广者-物料精选 )
	public function getmaterial($material_id,$item_id=0,$favorites_id=''){
		include ROOT_D.'/addons/jy_taobaoke/sdk/TopSdk.php';
		$c = new \TopClient;
		$basic=$this->plugin_setting('basic');
		$basic['siteid']=str_array($basic['siteid'],'_');
		$c->appkey = $basic['appkey'];
		$c->secretKey = $basic['secret'];
		$req = new \TbkDgOptimusMaterialRequest;
		$req->setPageSize("20");
		$req->setAdzoneId($basic['siteid'][3]);
		$req->setPageNo("1");
		$req->setMaterialId($material_id);
		$item_id=$item_id?:0;
		$req->setItemId($item_id);
		//$req->setFavoritesId($favorites_id);
		$re = $c->execute($req);
		//$re = json_decode($resp,true);
		$re   = (array)$re;
		if($re['code']==11){
			exi('开发者权限不足:'.$re['sub_code'],'error');
		}
		if($re['code']){
			exi('物料采集失败:'.$re['code'].'，错误详情：'.$re['sub_msg'].$re['msg'],'error');
		}
		$re   = (array)$re['result_list'];
		$re   = (array)$re['map_data'];
		return $re;
	}
	//已下架：taobao.tbk.uatm.favorites.get( 淘宝客-推广者-选品库宝贝列表 )
	public function getfavoritesrow(){
		include ROOT_D.'/addons/jy_taobaoke/sdk/TopSdk.php';
		$c = new \TopClient;
		$basic=$this->plugin_setting('basic');
		$c->appkey = $basic['appkey'];
		$c->secretKey = $basic['secret'];
		$req = new \TbkUatmFavoritesGetRequest;
		$req->setPageNo("1");
		$req->setPageSize("20");
		$req->setFields("favorites_title,favorites_id,type");
		$req->setType("1");
		$re = $c->execute($req);
		//$re = json_decode($resp,true);
		$re   = (array)$re;
		//print_r($re);exit;
		if($re['code']==11){
			exi('开发者权限不足:'.$re['sub_code'],'error');
		}
		$re   = (array)$re['results'];
		$re   = (array)$re['tbk_favorites'];
		return $re;
	}
	//已下架：taobao.tbk.uatm.favorites.item.get( 淘宝客-推广者-选品库宝贝信息 )
	public function getfavorites($adzone_id,$favorites_id,$page_no=1,$mid=0){
		include ROOT_D.'/addons/jy_taobaoke/sdk/TopSdk.php';
		$c = new \TopClient;
		$basic=$this->plugin_setting('basic');
		$c->appkey = $basic['appkey'];
		$c->secretKey = $basic['secret'];
		$req->setPlatform("2");//无线链接
		$req->setPageSize("20");
		$req->setAdzoneId($adzone_id);
		$req->setUnid($mid);
		$req->setFavoritesId($favorites_id);
		$req->setPageNo("2");
		$req->setFields("num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url,seller_id,volume,nick,shop_title,zk_final_price_wap,event_start_time,event_end_time,tk_rate,status,type");
		$resp = $c->execute($req);
		//$re = json_decode($resp,true);
		$re   = (array)$re;
		$re   = (array)$re['results'];
		$re   = (array)$re['n_tbk_item'];
		return $re;
	}
	//订单查询接口
	public function getorder($pageIndex=1,$pageSize=20,$type=1,$startTime='',$fields=array()){
		$startTime=$startTime?:time()-60;
		$param = array();
		$data['orderReq'] = array(
			'pageNo'=>$pageIndex,
			'pageSize'=>$pageSize,
			'type'=>$type,
			'time'=>$startTime,
		);
		$param['param_json'] = json_encode($data);
		$params = $this->sign_method('jd.union.open.order.query',$param);
		$res = $this->curl_post('https://router.jd.com/api', $params);
		$res = json_decode($res,true);
		if($res['code']!=0){
			exi('未获得《订单查询接口》API权限，请移步京东联盟申请','error');
		}
		$content=$res['jd_union_open_order_query_response']['result'];
		$content = json_decode($content,true);
		if($content['code']!=200){
			exi('获取订单失败，错误代码：'.$content['code'],'error');
		}
		return $content['data'];
	}
	public function creategoods($params){
						$num_iid=pdo_getcolumn('jy_taobaoke_goods',array('num_iid'=>$params['num_iid'],'uniacid'=>$_SESSION['uniacid']),'num_iid');
						if($num_iid){
							$goodsid=pdo_getcolumn('jy_taobaoke_goods',array('num_iid'=>$params['num_iid'],'uniacid'=>$_SESSION['uniacid']),'goodsid');
							$good=array(
										'title'=>$params['title'],
										'image'=>$params['pict_url'],
										'images'=>ijson_encode($params['small_images']['string']),
										'originalprice'=>$params['reserve_price'],
										'price'=>$params['zk_final_price'],
							);
							pdo_update('jy_weishop_goods',$good,array('id'=>$goodsid,'uniacid'=>$_SESSION['uniacid']));
							$taobao=array(
								'cat_name'=>$params['cat_name'],//主目录
								'cat_leaf_name'=>$params['cat_leaf_name'],//子目录
								'provcity'=>$params['provcity'],//商品所在地
								'tk_rate'=>$params['commission_rate'],//佣金比率
							);
							pdo_update('jy_taobaoke_goods', $taobao,array('num_iid'=>$params['num_iid'],'uniacid'=>$_SESSION['uniacid']));
							if($params['click_url']){
								pdo_update('jy_taobaoke_url', array('url'=>$params['click_url']),array('gid'=>$goodsid,'uniacid'=>$_SESSION['uniacid']));
							}
						}else{
							$good=array(
								'uniacid'=>$_SESSION['uniacid'],
								'title'=>$params['title'],
								'image'=>$params['pict_url'],
								'images'=>ijson_encode($params['small_images']['string']),
								'originalprice'=>$params['reserve_price'],
								'price'=>$params['zk_final_price'],
								'pluginname'=>'jy_taobaoke',
								'createtime'=>time()
								
							);
							pdo_insert('jy_weishop_goods',$good);
							$goodsid=pdo_insertid();
							$taobao=array(
								'uniacid'=>$_SESSION['uniacid'],
								'goodsid'=>$goodsid,
								'seller_id'=>$params['seller_id'],//卖家ID
								'nick'=>$params['nick'],//店铺名称
								'num_iid'=>$params['num_iid']?:$params['item_id'],//商品ID
								'cat_name'=>$params['cat_name'],//主目录
								'cat_leaf_name'=>$params['cat_leaf_name'],//子目录
								'item_url'=>$params['item_url']?:$params['click_url'],//商品链接,推广链接
								'provcity'=>$params['provcity'],//商品所在地
								'tk_rate'=>$params['commission_rate'],//佣金比率
								'createtime'=>time()
								
							);
							pdo_insert('jy_taobaoke_goods',$taobao);
							//$dd=ijson_encode($params);
							//file_put_contents(ROOT_D.'/11.TXT',$dd);
							if($params['click_url']){
								$iscode=pdo_get('jy_taobaoke_url',array('gid'=>$goodsid,'uniacid'=>$_SESSION['uniacid']),array('id','url'));
								if(!$iscode['url']){
									$url=$this->getduanurl($params['click_url']);
									pdo_insert('jy_taobaoke_url',array('gid'=>$goodsid,'url'=>$url,'uniacid'=>$_SESSION['uniacid']));
								}
							}
						}
				return $goodsid;
	}
	public function createorder($params){
				$orderId=pdo_getcolumn('jy_weishopke_order',array('orderid'=>$params['orderId'],'uniacid'=>$_SESSION['uniacid']),'orderid');
				$goodsid=pdo_getcolumn('jy_jdk_goods',array('skuId'=>$params['skuId'],'uniacid'=>$_SESSION['uniacid']),'goodsid');
				if($params['finishTime']){
						$status=1;
				}
				if(!$orderId){
					$new_order=array(
						'mid'=>$params['ext1'],
						'goodsid'=>$goodsid,
						'skuid'=>$params['skuId'],
						'orderid'=>$params['orderId'],
						'parentid'=>$params['parentId'],
						'goodsprice'=>$params['price'],
						'total'=>$params['skuNum'],
						'total_price'=>$params['estimateCosPrice'],
						'actualCosPrice'=>$params['actualCosPrice'],//实际计算佣金的
						'actualFee'=>$params['actualFee'],//推客获得的实际佣金（实际计佣金额*佣金比例*最终比例）。如订单完成后发生退款，此金额会更新
						'commissionRate'=>$params['commissionRate'],//佣金比例
						'estimateFee'=>$params['estimateFee'],//推客的预估佣金
						'type'=>'jd',
						'status'=>$status,
						'finishtime'=>$params['finishTime'],
						'createtime'=>$params['orderTime'],
					);
					pdo_insert('jy_weishopke_order',$new_order);
					$orderId=pdo_insertid();
				}else{
					
					$up_order=array(
						'total_price'=>$params['estimateCosPrice'],
						'actualCosPrice'=>$params['actualCosPrice'],
						'actualFee'=>$params['actualFee'],
						'commissionRate'=>$params['commissionRate'],
						'estimateFee'=>$params['estimateFee'],
						'status'=>$status,
						'finishtime'=>$params['finishTime'],
					);
					pdo_update('jy_weishopke_order',$up_order,array('orderid'=>$params['orderId'],'uniacid'=>$_SESSION['uniacid']));
				}
			return $orderId;
	}
	/*
		订单完成时，把佣金状态由初始的订单待完成升级为待结算
	*/
	public function order_complete($orderid){
		$this->update('order',array('status'=>1,'finishtime'=>TIMESTAMP),array('id'=>$orderid));
	}
	/*
		获取数据
	*/
	public function getinfo($appkey,$secret,$skuid=''){
		include ROOT_D.'/addons/jy_taobaoke/sdk/TopSdk.php';
		$c = new \TopClient;
		$c->appkey = $appkey;
		$c->secretKey = $secret;
		$req = new \TbkItemInfoGetRequest;
		$req->setNumIids($skuid);
		$req->setPlatform("1");
		$re = $c->execute($req);
		$re   = (array)$re;
		$re   = (array)$re['results'];
		$re   = (array)$re['n_tbk_item'];
		return $re;
	}
	/*
		创建结算单
	*/
	public function create_balance($mid){
		if(!$mid){
			exi('请先选择要结算的会员！','error');
		}
		//获取可结算佣金
		$params=array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid,'status'=>1);
		if($this->setting['balance_day']){
			//结算天数
			$time=TIMESTAMP-intval($this->setting['balance_day'])*86400;
			$params['finishtime <']=$time;
		}
		$commissions=$this->getall('order',$params);
		if(!$commissions){
			exi('没有可结算的佣金！','error');
		}
		$commission_num=count($commissions);
		$money=0;
		foreach($commissions as $commission){
			$money+=$commission['money'];
		}
		//结算最低佣金检测
		if($money<$this->setting['balance_money']){
			exi('可结算佣金太少，无法结算！','error');
		}
		$new_balance=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$mid,
			'balancesn'=>get_ordersn($this->tablename('order'),'balancesn','AC'),
			'commission_num'=>$commission_num,
			'money'=>$money,
			'createtime'=>TIMESTAMP,
			'status'=>0,
		);
		//结算手续费
		if($this->setting['balance_per']){
			$new_balance['balance_pay']=intval($new_balance['money']*$this->setting['balance_per'])/100;
		}else{
			$new_balance['balance_pay']=0;
		}
		$new_balance['final_money']=$new_balance['money']-$new_balance['balance_pay'];
		$this->insert('balance',$new_balance);
		$balance_id=pdo_insertid();
		foreach($commissions as $commission){
			$update=array(
				'status'=>2,
				'balancesn'=>$new_balance['balancesn'],
			);
			$this->update('order',$update,array('id'=>$commission['id']));
		}
		return $balance_id;
	}
	/*
		审核结算单
	*/
	public function check_balance($balance_id,$status,$remark=''){
		$update=array(
			'status'=>$status,
			'check_time'=>TIMESTAMP,
			'remark'=>$remark,
		);
		$this->update('balance',$update,array('id'=>$balance_id));
	}
	/*
		打款结算单
	*/
	public function pay_balance($balance_id,$pay_type,$wxgid=''){
		$balance=$this->get('balance',array('id'=>$balance_id,'uniacid'=>$_SESSION['uniacid']));
		if(!$balance || $balance['status']!=1){
			exi('结算单不存在或者不符合打款条件，打款失败！','error');
		}
		$pay_types=array_keys($this->pay_types);
		if(!$pay_type || !in_array($pay_type,$pay_types)){
			exi('未设置打款方式或者打款方式不合法，打款失败！','error');
		}
		$func_name='pay_balance_by_'.$pay_type;
		$trade_no=$this->$func_name($balance['mid'],$balance['final_money'],$balance['balancesn'],$wxgid);
		$update=array(
			'status'=>3,
			'pay_type'=>$pay_type,
			'pay_trade_no'=>$trade_no,
			'pay_time'=>TIMESTAMP,
		);
		$this->update('balance',$update,array('id'=>$balance['id']));
		return true;
	}
	/*
		打款到余额
	*/
	protected function pay_balance_by_credit($mid,$money,$balancesn){
		return cfc('core')->member_credit($mid,'credit2',$money,true,$this->plugin_name,$remark='分销佣金打款');
	}
	/*
		打款到微信零钱
	*/
	protected function pay_balance_by_wechat($mid,$money,$balancesn,$wxgid=''){
		if($wxgid){
			$wxapp=pdo_get('core_account_wxapp',array('id'=>$wxgid,'uniacid'=>$_SESSION['uniacid']),array('appid','mchid','paykey'));
		}
		$params=array(
			'appid'=>$wxapp['appid']?:'',
			'mch_id'=>$wxapp['mchid']?:'',
			'openid'=>$mid,
			'mch_billno'=>$balancesn,
			'money'=>$money,
			'wxgid'=>$wxgid,
			'remark'=>'电商客佣金发放',
		);
		$res=cfc('wechat_pay')->mch_pay($params);
		return $res['payment_no'];
	}
	/*
		打款到支付宝
	*/
	protected function pay_balance_by_alipay($mid,$money,$balancesn){
		exi('暂不支持打款到支付宝！','error');
	}
	/*
		打款到银行账户
	*/
	protected function pay_balance_by_union($mid,$money,$balancesn){
		exi('暂不支持打款到银行账户！','error');
	}
	
}
?>